<template>
  <div>
    <!-- 情况1：点击ALL PRODUCTS显示AllProducts组件 -->
    <AllProducts v-if="isShowAllProducts"/>

    <!-- 情况2：默认/点击其他导航, 显示区块” -->
    <div v-else>
      <!-- 轮播+推荐区 -->
      <div class="block-layer">
        <div class="block-center">
          <!-- 轮播区 -->
          <el-carousel
            class="carousel"
            indicator-position="outside"
            :autoplay="true"
            :interval="3000"
            @click="GoToAllProducts"
            >
            <el-carousel-item class="carousel-item" v-for="(item, index) in carouselList" :key="index" >
              <div class="slogan-text">
                <img :src="item.imageUrl" alt="image"/>
                <div class="carousel-text">
                  <h3 class="small justify-center" text="2xl">{{ item.tag }}</h3>
                  <p>{{ item.title }}</p>
                  <p>{{ item.description }}</p>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
          <!-- 推荐区 -->
          <div class="recommend-layer">
            <div class="recommend-top" @click="GoToAllProducts">
              <img :src="recommendList[0]" alt="recommend top">
            </div>
            <div class="recommend-down" @click="GoToAllProducts">
              <img :src="recommendList[1]" alt="recommend down">
            </div>
          </div>
        </div>
      </div>

      <div class="content-container">
        <div class="NewProductsSection" v-if="partitionList[0]">
          <ProductPartition :partition="partitionList[0]" />
        </div>
        <div class="TodayDeal">
          <TodayDeal />
        </div>
        <div class="FearuredProductsSection" v-if="partitionList[1]">
          <ProductPartition :partition="partitionList[1]" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="IndexPage">
import { onMounted, ref,onUnmounted, nextTick } from 'vue'
import ProductPartition from '@/components/product-partition/ProductPartition.vue'
import TodayDeal from '@/components/today-deal/TodayDeal.vue'
import AllProducts from '@/components/all-products/AllProducts.vue'
import emitter from '@/utils/emitter'

import { getBigBanners, getSmallBanners } from '@/api/banner.js'
import { getPartitions } from '@/api/partition.js'
import { getProductsByBrandId } from '@/api/brand'

const isShowAllProducts = ref(false);//初始AllProducts关闭

// 轮播图数据
const carouselList = ref([])
// 推荐数据
const recommendList = ref([])
// 分区数据
const partitionList = ref([])

const GoToAllProducts = () =>{
  isShowAllProducts.value = true//点击轮播区+推荐区去到ALL PRODUCRTS
}

// 1.处理“隐藏AllProducts并滚动”的事件
const handleHideAndScroll = async (className) => {
  isShowAllProducts.value = false// 先隐藏AllProducts（显示目标组件所在的默认区域）
  await nextTick()// 等待DOM更新（确保目标组件已渲染）
  scrollToTarget(className)// 执行滚动
}
// 2.通用滚动方法（抽离复用）
const scrollToTarget = (className) => {
  const targetElement = document.querySelector(`.${className}`)
  if (targetElement) {
    targetElement.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
  }
}

// 3. 加载所有必要数据（抽离为Promise，方便等待）
const loadAllData = async () => {
  // 并行加载轮播、推荐区、分区数据（首页核心数据）
  const [bannerRes, recommendRes, partitionRes] = await Promise.all([
    getBigBanners(),
    getSmallBanners(),
    getPartitions()
  ])

  // 处理轮播图数据
  bannerRes.data.forEach(v => v.imageUrl = import.meta.env.VITE_APP_BASE_FILE + v.imageUrl)
  carouselList.value = bannerRes.data

  // 处理推荐区数据
  recommendList.value = recommendRes.data.map(v => import.meta.env.VITE_APP_BASE_FILE + v.imageUrl)

  // 处理分区数据（关键：目标组件依赖此数据渲染）
  partitionList.value = partitionRes.data
}

onMounted(async () => {
  // ① 先加载所有核心数据（确保组件能渲染）
  await loadAllData()

  // ② 监听导航栏事件（不变）
  emitter.on('show-all-products', () => {
    isShowAllProducts.value = true
  })
  emitter.on('hide-all-products-and-scroll', handleHideAndScroll)

  // 延迟处理参数，确保DOM完全渲染
  setTimeout(() => {
    const urlParams = new URLSearchParams(window.location.search)
    const scrollToClassName = urlParams.get('scrollTo')
    const needShowAll = urlParams.get('showAllProducts')

    if (scrollToClassName) {
      scrollToTarget(scrollToClassName)
    } else if (needShowAll === 'true') {
      isShowAllProducts.value = true
    }
  }, 100) // 短暂延迟确保DOM就绪

  // ③ 处理跨页面传递的指令参数
  const urlParams = new URLSearchParams(window.location.search)
  const scrollToClassName = urlParams.get('scrollTo') // 滚动指令
  const needShowAll = urlParams.get('showAllProducts') // 显示AllProducts指令

  if (scrollToClassName) {
    // 执行滚动（此时partitionList已加载，组件已渲染）
    nextTick(() => {
      scrollToTarget(scrollToClassName)
    })
  } else if (needShowAll === 'true') {
    // 显示AllProducts
    isShowAllProducts.value = true
  }
})

// 页面卸载：清除事件监听（避免内存泄漏）
onUnmounted(() => {
  emitter.off('show-all-products')
  emitter.off('hide-all-products-and-scroll', handleHideAndScroll)
})

</script>

<style scoped lang="scss">
 /* 最外层,铺满整个父级区 */
.block-layer {
  width: 100%;
  height: 480px;
  // height: 30%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;

  /* 第二层: 轮播+推荐 */
  .block-center {
    background-color: #fff;
    width: 64%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    // 轮播图
    .carousel {
      // height: 100%;
      height: 480px;
      width: 63%;
      cursor: pointer;

      .carousel-item {
        width: 100%;
        height: 100%;
        height: 480px;
        /* 装轮播图、标题文字的容器 */
        .slogan-text {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          position: relative;

          img {
            width: 100%;
            // height: 100%;
            object-fit: cover;
          }

          /* 轮播图上文字*/
          .carousel-text {
            position: absolute;
            top: 50%;
            right: 5%;
            width: 50%;
            transform: translateY(-50%);
            color: #fff;
            text-align: right;
            padding: 20px;
            box-sizing: border-box;

            h3 {
              /* font-family: Montserrat !important;字体 */
              font-size: 18px;
              font-weight: 400;
              color: #fff;
              margin: 0 0 0px 0; /* 与下方title间距 */
            }

            /* title*/
            p:first-of-type {
              font-size: 36px; /* 明显放大 */
              font-weight: 720;
              color: #BEAE59;
              margin: 0 0 0px 0; /* 与下方desc间距 */
            }

            /* desc*/
            p:last-of-type {
              font-size: 16px;
              line-height: 1.4; /* 行高增强可读性 */
              color: #fff;
              margin: 0;
            }

          }

        }
      }

    }

    // 推荐区
    .recommend-layer {
      width: 35%;
      display: flex;
      height: 100%;
      background-color: #fff;
      box-sizing: border-box;
      flex-direction: column;
      // gap: 4%;
      gap: 30px;

      .recommend-top, .recommend-down {
        cursor: pointer;
        width: 100%;
        height: 48%;
        display: flex;
        align-items: center;
        img {
          width: 100%;
          // height: 100%;
          object-fit: cover;
        }
      }

    }
  }

}

:deep(.el-carousel__indicators) {
  display: none;
}

:deep(.el-carousel, .el-carousel__item, .el-carousel__container) {
  height: 100%;
}

/* 指示器样式 */
// .el-carousel__indicators--bottom {
//   bottom: 24px; /* 与文字区域拉开距离 */
//   left: 50%;
//   transform: translateX(-50%);
// }

/* 其他 */
.NewProductsSection {
  margin-top: 120px;
}
.TodayDeal {
  margin-top: 120px;
}
.FearuredProductsSection {
  margin-top: 120px;
}
</style>

